/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Select } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;

const ScPriceForm = ({ priceId, modal, onSubmit, onCancel }) => {
  const { lineTimeStore: store } = useStore();
  const { show, record, toClose } = modal;
  const isViewMode = show === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [line] = useState(() => observable({}));

  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (toClose?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (priceId) {
        const data = await store.get(priceId);
        const { type, companyId, fromCityId, toCityId, offStationId, onStationId } = data;
        editCtx.origin = _.cloneDeep(data);
        _.assign(line, data);

        if (type === 2) {
          // 专线
          const city = await store.getScCity({ companyId });
          store.fromCity = city;
          const toCity = await store.getScCity({ fromCity: fromCityId });
          store.toCity = toCity;
          const start = await store.getScStation({ fromCities: [fromCityId], toCities: [toCityId], direction: '0', toStation: offStationId, priceType: 2 });
          const end = await store.getScStation({ fromCities: [fromCityId], toCities: [toCityId], direction: '1', fromStation: onStationId, priceType: 2 });
          store.startStation = start;
          store.endStation = end;
        } else if (type === 3) {
          // 巴士
          const city = await store.getBusCity({ companyId });
          store.fromCity = city;
          const toCity = await store.getBusCity({ fromCity: fromCityId });
          store.toCity = toCity;
          const start = await store.getBusStation({ fromCities: [fromCityId], toCities: [toCityId], direction: '0', toStation: offStationId, priceType: 3 });
          const end = await store.getBusStation({ fromCities: [fromCityId], toCities: [toCityId], direction: '1', fromStation: onStationId, priceType: 3 });
          store.startStation = start;
          store.endStation = end;
        }
      } else {
        // 添加操作,设置默认值
        _.set(line, 'type', store._lineStatus);
        _.set(line, 'enable', true);
      }
    })();
  }, []);


  useEffect(() => {
    (async () => {
      const { _lineStatus } = store;
      const { companyId } = line;
      if (_lineStatus === '3') {
        const city = await store.getBusCity({ companyId });
        store.fromCity = city;
      } else if (_lineStatus === '2') {
        // 专线
        const city = await store.getScCity({ companyId });
        store.fromCity = city;
      }
    })();
  }, [toJS(line.companyId)]);

  if (!line) return <></>;

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
    fromCityId: {
      label: t`开始城市`,
      ui: {
        renderer: (v) => <TauSimpleSelect hasClear disabled={priceId} value={v || ''} dataSource={store.fromCity} onChange={(_, __, l) => handleFromCity(l)} />,
        itemProps: {
          required: true,
        },
      },
    },
    toCityId: {
      label: t`结束城市`,
      ui: {
        renderer: (v) => <TauSimpleSelect hasClear disabled={priceId} value={v || ''} dataSource={store.toCity} onChange={(_, __, l) => handleToCity(l)} />,
        itemProps: {
          required: true,
        },
      },
    },
    onStationId: {
      label: t`开始站点`,
      ui: {
        renderer: (v) => <TauSimpleSelect hasClear disabled={priceId} value={v || ''} onChange={(_, __, l) => handleStartStation(l)} dataSource={store.startStation} />,
        itemProps: {
          required: true,
        },
      },
    },
    offStationId: {
      label: t`结束站点`,
      ui: {
        renderer: (v) => <TauSimpleSelect hasClear disabled={priceId} value={v || ''} onChange={(_, __, l) => handleEndStation(l)} dataSource={store.endStation} />,
        itemProps: {
          required: true,
        },
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;

    _.set(line, name, value);

    (async () => {
      const { _lineStatus } = store;
      // 如果是开始城市
      if (name === 'fromCityId') {
        // 如果是巴士
        if (_lineStatus === '3') {
          const end = await store.getBusCity({ fromCity: value });
          _.set(line, 'onStationId', '');
          _.set(line, 'offStationId', '');
          _.set(line, 'toCityId', '');
          store.toCity = [];
          store.startStation = [];
          store.endStation = [];
          store.toCity = end;
        } else if (_lineStatus === '2') {
          store.toCity = [];
          store.startStation = [];
          store.endStation = [];
          _.set(line, 'onStationId', '');
          _.set(line, 'offStationId', '');
          _.set(line, 'toCityId', '');
          const city = await store.getScCity({ formCity: value });
          store.toCity = city;
        }
      }
      // 如果是结束城市
      if (name === 'toCityId') {
        if (_lineStatus === '3') {
          const start = await store.getBusStation({ fromCities: [line.fromCityId], toCities: [value], direction: '0', priceType: 3 });
          store.startStation = start;
        } else if (_lineStatus === '2') {
          const start = await store.getScStation({ fromCities: [line.fromCityId], toCities: [value], direction: '0', priceType: 2 });
          store.startStation = start;
        }
      }
      // 如果是开始站点
      if (name === 'onStationId') {
        if (_lineStatus === '3') {
          if (value === undefined) {
            _.set(line, 'onStationId', '');
          } else {
            const end = await store.getBusStation({ fromCities: [line.fromCityId], toCities: [line.toCityId], fromStation: value, direction: '1', priceType: 3 });
            store.endStation = end;
          }
        } else if (_lineStatus === '2') {
          if (value === undefined) {
            _.set(line, 'onStationId', '');
          } else {
            const end = await store.getScStation({ fromCities: [line.fromCityId], toCities: [line.toCityId], fromStation: value, direction: '1', priceType: 2 });
            store.endStation = end;
          }
        }
      }
      // 如果是结束站点
      if (name === 'offStationId') {
        if (_lineStatus === '3') {
          // const findStation = store.endStation?.find((p) => p.value === value);
          const start = await store.getBusStation({ fromCities: [line.fromCityId], toCities: [line.toCityId], toStation: value, direction: '0', priceType: 3 });
          store.startStation = start;
          _.set(line, 'offStationId', value || '');
        } else if (_lineStatus === '2') {
          if (value === undefined) {
            _.set(line, 'offStationId', '');
          } else {
            const start = await store.getScStation({ fromCities: [line.fromCityId], toCities: [line.toCityId], toStation: value, direction: '0', priceType: 2 });
            store.startStation = start;
          }
        }
      }
    })();

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  /**
   * 监听开始站点
   * @param {*} l 对象模型
   */
  const handleStartStation = (l) => {
    if (l) {
      const { label } = l;
      _.set(line, 'onStationName', label);
    } else {
      _.set(line, 'onStationName', '');
      _.set(line, 'startStationId', '');
      _.set(line, 'onStationId', '');
    }
  };

  /**
   * 监听结束站点
   * @param {*} l 对象模型
   */
  const handleEndStation = (l) => {
    if (l) {
      const { label } = l;
      _.set(line, 'offStationName', label);
    } else {
      _.set(line, 'offStationName', '');
      _.set(line, 'endStationId', '');
      _.set(line, 'offStationId', '');
    }
  };
  /**
   * 监听开始城市
   * @param {*} l 对象模型
   */
  const handleFromCity = (l) => {
    if (l) {
      const { label } = l;
      _.set(line, 'fromCityName', label);
    } else {
      _.set(line, 'fromCityName', '');
    }
  };
  /**
   * 监听结束城市
   * @param {*} l 对象模型
   */
  const handleToCity = (l) => {
    if (l) {
      const { label } = l;
      _.set(line, 'toCityName', label);
    } else {
      _.set(line, 'toCityName', '');
    }
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (_value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: LineTimeForm.jsx:267 _ errors:', errors);
      return;
    }
    onSubmit?.(line);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={line}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`线路信息`} />
      <FieldsGrid
        formData={line}
        overrideModel={overrideModel}
        mode={show}
        fields={['fromCityId', 'toCityId', 'onStationId', 'offStationId']}
      />
      <TitleGrid title={t`时长信息`} />
      <FieldsGrid
        formData={line}
        overrideModel={overrideModel}
        mode={show}
        fields={['duration', 'mileage']}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(ScPriceForm);
